#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;

#define CODE_LENGTH 6
#define NAME_LENGTH 8

typedef struct {
    char code[CODE_LENGTH];
    int score;
    char name[NAME_LENGTH];
} student;

void print_student(student[], int);
void swap_element(student[], int, int);
bool compare_element(student, student, int);
void quick_sort(student[], int, int);

int main()
{
    int num, order_code, case_num = 0;
    while (scanf("%d %d", &num, &order_code) != EOF) {
        if (num == 0) 
            break;

        student *student_list = (student *)malloc(sizeof(student) * num);
        for (int i = 0; i < num; i++) {
            scanf("%s %s %d", student_list[i].code, 
                student_list[i].name, &student_list[i].score);
        }

        quick_sort(student_list, num, order_code);
        printf("Case %d:\n", ++case_num);
        print_student(student_list, num);
    }
}

void print_student(student array[], int num)
{
    for (int i = 0; i < num; i++) {
        // printf(">> ");
        for (int j = 0; j < CODE_LENGTH; j++)
            printf("%c", array[i].code[j]);
        printf(" %s", array[i].name);
        printf(" %d\n", array[i].score);
    }
}

void swap_element(student array[], int i, int j) 
{
    // int temp;
    // temp = array[i];
    int temp_score;
    char temp_code[CODE_LENGTH], temp_name[NAME_LENGTH];
    temp_score = array[i].score;
    strncpy(temp_code, array[i].code, CODE_LENGTH);
    strcpy(temp_name, array[i].name);
    // array[i] = array[j];
    array[i].score = array[j].score;
    strncpy(array[i].code, array[j].code, CODE_LENGTH);
    strcpy(array[i].name, array[j].name);
    // array[j] = temp;
    array[j].score = temp_score;
    strncpy(array[j].code, temp_code, CODE_LENGTH);
    strcpy(array[j].name, temp_name);
}

// if a > b, return true
bool compare_element(student a, student b, int order_code)
{
    int a_code = atoi(a.code);
    int b_code = atoi(b.code);
    if (order_code == 1) {
        return a_code > b_code;
    } else if (order_code == 2) {
        if (strcmp(a.name, b.name) != 0)
            return strcmp(a.name, b.name) > 0;
        else
            return a_code > b_code;
    } else {
        if (a.score != b.score)
            return a.score > b.score;
        else
            return a_code > b_code;
    }
}

void quick_sort(student array[], int num, int order_code) 
{
    int i, last = 0;
    if (num <= 1)
        return;
    swap_element(array, 0, rand() % num);
    for (i = 1; i < num; i++) {
        if (!compare_element(array[i], array[0], order_code))
            swap_element(array, ++last, i);
    }

    swap_element(array, 0, last);
    quick_sort(array, last, order_code);
    quick_sort(array + last + 1, num - last - 1, order_code);
}
